package networking;

import gameStates.absGamesStates.network.AbsServerState;
import logic.common.game.Game;
import logic.common.player.Player;
import logic.common.team.Team;

public class PingThread extends Thread {
	
	private Team teamA, teamB;
	private boolean keepAlive;
	private Game game;
	private AbsServerState serverState;
	
	public PingThread(AbsServerState serverState) {
		super();
		this.serverState = serverState;
		
		game = serverState.getIngameState().getGame();
		
		teamA = game.getTeamA();
		teamB = game.getTeamB();
		
		keepAlive = true;
	}
	
	@Override
	public void run() {
		while(keepAlive) {
			updatePings(teamA);
			updatePings(teamB);
			
			try { sleep(1000); }
			catch(Exception e) { e.printStackTrace(); }
		}
	}
	
	public void killThread() { keepAlive = false; }
	
	private void updatePings(Team team) {
		for(Player player : team.getHumanPlayers()) {
			if(game.getCurrentPlayer() != player) {
				updatePing(player);
			}
		}
	}
	
	private void updatePing(Player player) {
		short playerShortID = serverState.getPlayerShortID(player.getID());
		serverState.sendPingMessage(playerShortID);
	}
}